<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .content {
            position: relative;
            width: 400px;
            height: 400px;
            margin: 50px;
            border: lightgreen solid 20px;
        }

        .box {
            /* position: relative; */
            margin: 50px;
            height: 200px;
            width: 200px;
            padding: 50px;
            background-color: lightpink;
        }

        .inner {
            width: 70px;
            height: 70px;
            background-color: rgb(123, 123, 33);
        }
    </style>
</head>

<body>
    <div class="content">
        <div class="box">
            <div class="inner">

            </div>
        </div>
    </div>

    <script>
        // 获取任意元素距离页面顶端的距离
        var content = document.querySelector('.content');
        var box = document.querySelector('.box');
        var inner = document.querySelector('.inner');

        var obj = getPosition(inner);
        console.log(obj);
        // 递归的获取offsetParent元素的offsetTop/Left 和clientTop/Left
        function getPosition(el) {
            // 跳出递归条件
            if (el.offsetParent === document.body) {
                return {
                    top: el.offsetTop,
                    left: el.offsetLeft
                }
            }
            var obj = getPosition(el.offsetParent);
            return {
                top: el.offsetTop + el.offsetParent.clientTop + obj.top,
                left: el.offsetLeft + el.offsetParent.clientLeft + obj.left
            }
        }
    </script>
</body>

</html>